/*
 *                        _oo0oo_
 *                       o8888888o
 *                       88" . "88
 *                       (| -_- |)
 *                       0\  =  /0
 *                     ___/`---'\___
 *                   .' \\|     |// '.
 *                  / \\|||  :  |||// \
 *                 / _||||| -:- |||||- \
 *                |   | \\\  - /// |   |
 *                | \_|  ''\---/''  |_/ |
 *                \  .-\__  '-'  ___/-. /
 *              ___'. .'  /--.--\  `. .'___
 *           ."" '<  `.___\_<|>_/___.' >' "".
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /
 *      =====`-.____`.___ \_____/___.-`___.-'=====
 *                        `=---='
 *
 *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 *            佛祖保佑     永不宕机     永无BUG
 *
 *        佛曰:
 *                写字楼里写字间，写字间里程序员；
 *                程序人员写程序，又拿程序换酒钱。
 *                酒醒只在网上坐，酒醉还来网下眠；
 *                酒醉酒醒日复日，网上网下年复年。
 *                但愿老死电脑间，不愿鞠躬老板前；
 *                奔驰宝马贵者趣，公交自行程序员。
 *                别人笑我忒疯癫，我笑自己命太贱；
 *                不见满街漂亮妹，哪个归得程序员？
 *
 * @Date: 2023-05-23 13:38:23
 * @LastEditors: lijingang
 * @LastEditTime: 2023-08-25 14:26:01
 * @FilePath: /ds-brain-web/src/utils/util/index.js
 */

import Jsencrypt from 'jsencrypt'
import * as CryptoJS from 'crypto-js'

export function generateEntype(word) {
  const publicKey = `
                    -----BEGIN PUBLIC KEY-----
            MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk26KSyRlcMHaya6GrT5v
            Ysl3njjjBavEdGOiyr6BjpCBD+nZ184vlJzwRHq1Paow9UF0XuR0WwD8srEgluJd
            Zp1WqjcYeXpd+Rh4E64fAVwLgAnhNShz1g4b9jauqf0+KnDzL9UCoRogXiZeIRTN
            WV0FaQytADXFbVP4yw8X8u3d7nCoRYNKIm5UhqCiDg5NviuFVTNbhlbWZn9sbfGj
            tJfiZlXXJS7YHdX7elBM0ylupXqb5yJUZroPJoIYxGC+JNrf4udSxMCSHdccSqwo
            M2E9/Avh6aW2/ulDKs4Qv8Mv2I+cOwzJSovJpHJlnFqnQhkmpCbZSTZcbLK5CmWf
            GQIDAQAB
            -----END PUBLIC KEY-----
        `
  const encrypt = new Jsencrypt()
  encrypt.setPublicKey(publicKey)
  const encryptPwd = encrypt.encrypt(word)
  return encryptPwd
}

// 设置cookie
export function setCookie(name, value, day) {
  var date = new Date()
  date.setDate(date.getDate() + day)
  document.cookie = name + '=' + value + ';expires=' + date
}
// 获取cookie
export function getCookie(name) {
  var reg = RegExp(name + '=([^;]+)')
  var arr = document.cookie.match(reg)
  if (arr) {
    return arr[1]
  } else {
    return ''
  }
}
// 删除cookie
export function delCookie(name) {
  setCookie(name, null, -1)
}
// 分组
// 分组
export function arrayToTree(items, key, parentKey) {
  const res = []
  const data = JSON.parse(JSON.stringify(items))
  const idMapping = data.reduce((prev, cur, i) => {
    prev[cur[key]] = i
    return prev
  }, {})
  data.forEach((el) => {
    if (el[parentKey] === -1 || !el[parentKey]) {
      return res.push(el)
    }
    const parentEl = data[idMapping[el[parentKey]]]
    parentEl.children = [...(parentEl.children || []), el]
  })
  console.log('el', res)
  return res
}

/**
 *加密处理
 */
export const encryption = (params) => {
  const { data, type, param, key } = params
  const result = JSON.parse(JSON.stringify(data))
  var SECRET_IV = CryptoJS.enc.Latin1.parse(key)
  var SECRET_KEY = CryptoJS.enc.Latin1.parse(key)
  if (type === 'Base64') {
    param.forEach((ele) => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach((ele) => {
      var data = result[ele]
      // 加密
      var encrypted = CryptoJS.AES.encrypt(data, SECRET_KEY, {
        iv: SECRET_IV,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding
      })
      result[ele] = encrypted.toString()
    })
  }
  return result
}
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
export function groupByKey(arr, key) {
  const data = JSON.parse(JSON.stringify(arr))
  const groupMap = data.reduce((prev, cur) => {
    if (!prev[cur[key]]) {
      prev[cur[key]] = []
    }
    prev[cur[key]].push(cur)
    return prev
  }, {})
  return Object.keys(groupMap).map((item) => ({
    [key]: item,
    children: groupMap[item]
  }))
}
